import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => { // 每次请求真正发起之前, 会先执行这里一次
    // config 请求配置对象

    // 在后续的接口请求中, 如果已经有token了, 携带在请求头中带给后台表明身份在后端权限认证
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }

    // 会return到当前本次请求axios函数内
    return config
  },
  error => {
    console.log(111)
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => { // axios内部会判断, 后端返回设置的响应http状态码为2xx, 3xx就会执行这里
    // response的值是一个axios封装对象, {config, data, headers, request, status}
    // data字段里的值才是后端返回的真正的数据对象
    const res = response.data // res的值就是后端返回的那个对象{ code, data }

    // if the custom code is not 20000, it is judged as an error.
    // 20000为成功
    if (res.code !== 20000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload() // 强制刷新浏览器
          })
        })
      }
      // 返回的axios调用处原地的那个Promise对象位置
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // 返回到axios函数调用后Promise对象位置
      return res
    }
  },
  error => { // http状态码为4xx, 5xx进这里
    console.log('err' + error) // for debug
    // 报错了会有个统一的错误提示弹窗
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    // return到axios调用后原地的那个Promise对象位置
    // return Promise.reject(error)
    /**
     * 等同于
     * return new Promise((resolve, reject) => {
     *  reject(error)
     * })
     */
    // 返回一个新的Promise对象, 状态为失败状态并传error值
    return Promise.reject(error)
  }
)

// 导出 自定义的axios实例方法
export default service
